package com.pig4cloud.pigx.user.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.strategy.api.feign.StrategyContractFeign;
import com.pig4cloud.pigx.user.entity.User;
import com.pig4cloud.pigx.user.enums.UserEnums;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 用户等级持续更新
 */
@Component
@EnableScheduling
@AllArgsConstructor
@Slf4j
public class UserLevelUpTask {

	private final StrategyContractFeign contractFeign;

	@Scheduled(fixedDelay = 1000)
	public void task() {
		List<User> userList = new User().selectList(new QueryWrapper<User>() {{
			ge("community_count", 50);
			ge("direct_invitation_count",10);
		}});
		for (User user : userList) {
			List<User> users = new User().selectList(new QueryWrapper<User>() {{
				eq("parent_id", user.getId());
			}});
			int count = 0;
			for (User u : users) {
				Long data = contractFeign.userStartStrategyCount(u.getId(), SecurityConstants.FROM_IN).getData();
				if (data > 0) {
					count += 1;
				}
			}
			if (count >= 10) {
				user.setLevel(UserEnums.Level.LEVEL_1.getValue());
				if (user.getCommunityCount() > 120) {
					user.setLevel(UserEnums.Level.LEVEL_2.getValue());
				}
			} else {
				user.setLevel(UserEnums.Level.LEVEL_0.getValue());
			}
			user.updateById();
		}
	}

}
